package com.zhihao.zhihaopicturebackend.exception;

/**
 * @author Jackson
 * @create 2024/12/19 13:29
 * @description 异常处理工具类(一行代码即可抛出异常,替代if-3，类似assert断言类方法)
 */
public class ThrowUtils {

    // 函数重载
    /**
     * 条件成立则抛异常
     *
     * @param condition        条件
     * @param runtimeException 异常
     */
    public static void throwIf(boolean condition, RuntimeException runtimeException) {
        if (condition) {
            throw runtimeException;
        }
    }

    /**
     * 条件成立则抛异常
     *
     * @param condition 条件
     * @param errorCode 错误码
     */
    public static void throwIf(boolean condition, ErrorCode errorCode) {
        throwIf(condition, new BusinessException(errorCode));
    }

    /**
     * 条件成立则抛异常
     *
     * @param condition 条件
     * @param errorCode 错误码
     * @param message   错误信息
     *  eg:
     *      if(zhihao==null){throw new BusinessException(10086,"异常错误")}
     *      ThrowUtils.throwIf(zhihao==null, new BusinessException(10086,"异常错误"))
     *
     *      if(zhihao==null){throw new BusinessException(ErrorCode.NO_AUTH_ERROR)}
     *      ThrowUtils.throwIf(zhihao==null, ErrorCode.NO_AUTH_ERROR)
     *
     *      if(noAuth){throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"没权限")}
     *      ThrowUtils.throwIf(noAuth, ErrorCode.NO_AUTH_ERROR, "没权限")
     */
    public static void throwIf(boolean condition, ErrorCode errorCode, String message) {
        throwIf(condition, new BusinessException(errorCode, message));
    }
}